<?php

namespace App\Http\Controllers\Admin;

use App\Facades\CustomPassword;
use App\Http\Requests\Admin\PersonalManage\StoreRegRequest;
use App\Models\Admin\Collection\CollectionTrackResume;
use App\Models\Common\CollOption;
use App\Models\Personal\PersonalUser;
use App\Models\Personal\Resume;
use App\Models\XS\ResumeXS;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Style;

class PersonalManageController extends CommonController{
    public function __construct(){
    }

    /**
     * 审核简历
     * @param Request $request
     * @return mixed
     */
    public function auditResume(Request $request){
        $input = $request->only('keyword', 'type');
        $type = trim($request->type);
        $keyword = trim($request->keyword);
        $resume = DB::table('personal_users as t1')
            ->join('resume as t2', 't1.uid', '=', 't2.uid')
            ->select(
                't1.uid',
                't2.name', 't2.birthday', 't2.education', 't2.intentionjobs', 't2.mobile', 't2.id', 't2.regtime'
            )->where(function($query) use ($keyword){
                if(strlen($keyword) > 0){
                    $query->where('t2.name', 'like', '%' . $keyword . '%')
                        ->orWhere('t2.mobile', 'like', '%' . $keyword . '%')
                        ->orWhere('t2.intentionjobs', 'like', '%' . $keyword . '%')
                        ->orWhere('t2.id',$keyword);
                }
            })->where(function($query) use ($type){
                if(strlen($type) > 0){
                    if($type == '0'){
                        $query->where('t2.resume_status', $type)
                            ->orWhere('t2.review', $type);
                    }else{
                        $query->where('t2.resume_status', $type);
                    }
                }
            })
            ->orderBy('t2.updatetime', 'desc')
            ->paginate(20);
        foreach($resume as $v){
            $v->education = ($v->education) ? CollOption::getOptionName($v->education, 'education') : '初中';
            //代表这个简历是不是采集添加审核过来的
            $collectionTrackResume = CollectionTrackResume::where('real_resume_id', $v->id)->first();
            if(!empty($collectionTrackResume)){
                $v->collectionResumeID = 1;
            }
        }
        //分页分配参数 过滤boolean假值
        $appends = arrayFilter($input);
        return Style::view('admin.personal_manage.audit_resume', compact('resume', 'appends', 'type'));
    }

    /**
     * 驳回简历
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function dismissedResume(Request $request){
        $resume_id = $request->input('selected_id.*');
        foreach($resume_id as $k => $v){
            Resume::where('id', $v)->update([
                'resume_status' => 5,
                'review' => 1,
                'updatetime' => date('Y-m-d H:i:s', time()),
                'xs_status' => 0
            ]);
        }
        flash('驳回简历成功！', 'success');
        return redirect()->back();
    }

    /**
     * 通过审核
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function approved(Request $request){
        $resume_id = $request->input('selected_id.*');
        foreach($resume_id as $k => $v){
            $resume = Resume::where('id', $v)->first(['bkresume_status']);
            Resume::where('id', $v)->update([
                'resume_status' => $resume->bkresume_status,
                'updatetime' => date('Y-m-d H:i:s', time()),
                'review' => 1,
                'xs_status' => 0
            ]);
        }
        flash('审核成功', 'success');
        return redirect()->back();
    }

    /**
     * 删除简历
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delResume(Request $request){
        $result = Resume::where('id', $request->id)->update([
            'resume_status' => 4,
            'updatetime' => date('Y-m-d H:i:s', time()),
            'review' => 1,
            'xs_status' => 0
        ]);
        if($result){
            return response()->json(['status' => 0, 'msg' => '简历删除成功！']);
        }else{
            return response()->json(['status' => 1, 'msg' => '简历删除失败，请稍后重试！']);
        }
    }

    /**
     * 批量删除简历
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function batchDelResume(Request $request){
        $resume_id = $request->input('selected_id.*');
        foreach($resume_id as $k => $v){
            Resume::where('id', $v)->update([
                'resume_status' => 4,
                'review' => 1,
                'updatetime' => date('Y-m-d H:i:s', time()),
                'xs_status' => 0
            ]);
        }
        flash('批量删除简历成功！', 'success');
        return redirect()->back();
    }

    /**
     * 修改注册信息
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function jobModTwo(Request $request, $id){
        $user = PersonalUser::where('uid', $id)->first(['username', 'password', 'email', 'regtime', 'uid', 'mobile', 'email_id', 'mobile_id', 'qqopenid', 'wechatopenid']);
        return Style::view('admin.personal_manage.job_mod_two', compact('user'));
    }

    /**
     * 提交注册信息
     * @param StoreRegRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function jobStoreTwo(StoreRegRequest $request){
        $input = $request->only(['uid', 'username', 'password', 'email', 'uid', 'mobile', 'email_id', 'mobile_id', 'qqopenid', 'wechatopenid']);
        $user = PersonalUser::where('uid', $request->uid)->first(['password']);
        if($user->password != $input['password']){
            $input['password'] = CustomPassword::make($request->input('password'));
        }
        $input['username'] = !empty(trim($request->username)) ? trim($request->username) : null;
        $input['updatetime'] = date('Y-m-d,H:i:s', time());
        $input['mobile'] = !empty(trim($request->mobile)) ? trim($request->mobile) : null;
        $input['qqopenid'] = !empty(trim($request->qqopenid)) ? trim($request->qqopenid) : null;
        $input['wechatopenid'] = !empty(trim($request->wechatopenid)) ? trim($request->wechatopenid) : null;
        $result = PersonalUser::where('uid', $request->uid)->update($input);
        if($result){
            flash('更新用户成功', 'success');
            return redirect('admin/audit_resume');
        }else{
            return back()->with('errors', '用户信息更新失败，请稍后重试！');
        }
    }

    /**
     * 个人账户中心登录
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function personalWelcome(Request $request, $id){
        if(auth()->guard('personal')->loginUsingId($id)){
            return redirect('personal/welcome');
        }else{
            return redirect('admin/audit_resume');
        }
    }

    /**
     * 用户注册信息
     * @param Request $request
     * @return mixed
     */
    public function jobUserReg(Request $request){
        $keyword = trim($request->keyword);
        $user = PersonalUser::select(['uid', 'username', 'mobile', 'email', 'regtime', 'email_id', 'email_id', 'mobile_id', 'qqopenid', 'wechatopenid'])
            ->orderBy('regtime', 'desc')
            ->where(function($query) use ($keyword){
                if(strlen($keyword) > 0){
                    $query->where('username', 'like', '%' . $keyword . '%')
                        ->orWhere('mobile', 'like', '%' . $keyword . '%');
                }
            })
            ->paginate(20);
        return Style::view('admin.personal_manage.job_user_reg', compact('user'));
    }

    /**
     * 修改注册信息
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function jobUserMod(Request $request, $id){
        $user = PersonalUser::where('uid', $id)->first(['username', 'password', 'email', 'regtime', 'uid', 'mobile',
            'email_id', 'mobile_id', 'qqopenid', 'wechatopenid', 'device_token', 'wechatmpopenid', 'wechatunionid']);
        return Style::view('admin.personal_manage.job_user_mod', compact('user'));
    }

    /**
     * 提交注册信息
     * @param StoreRegRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function jobUserStore(StoreRegRequest $request){
        $input = $request->only(['uid', 'username', 'password', 'email', 'uid', 'mobile', 'email_id', 'mobile_id', 'qqopenid', 'wechatopenid']);
        $user = PersonalUser::where('uid', $request->uid)->first(['password']);
        if($user->password != $input['password']){
            $input['password'] = CustomPassword::make($request->input('password'));
        }
        $input['username'] = !empty(trim($request->username)) ? trim($request->username) : null;
        $input['updatetime'] = date('Y-m-d,H:i:s', time());
        $input['mobile'] = !empty(trim($request->mobile)) ? trim($request->mobile) : null;
        $input['qqopenid'] = !empty(trim($request->qqopenid)) ? trim($request->qqopenid) : null;
        $input['wechatopenid'] = !empty(trim($request->wechatopenid)) ? trim($request->wechatopenid) : null;
        $input['device_token'] = !empty(trim($request->device_token)) ? trim($request->device_token) : null;
        $input['wechatmpopenid'] = !empty(trim($request->wechatmpopenid)) ? trim($request->wechatmpopenid) : null;
        $input['wechatunionid'] = !empty(trim($request->wechatunionid)) ? trim($request->wechatunionid) : null;

        try{
            $result = PersonalUser::where('uid', $request->uid)->update($input);
            if($result){
                flash('修改个人用户成功', 'success');
                return redirect('admin/job_user_reg');
            }else{
                return back()->with('errors', '用户信息更新失败，请稍后重试！');
            }
        }catch(\PDOException $e){
            return back()->with('errors', '用户信息更新失败，可能QQ、微信、IOS绑定数据重复！');
        }
    }

    /**
     * 简历批量刷新
     * @param Request $request
     * @return mixed
     */
    public function resumeAdminRefresh(Request $request){
        $input = $request->only('keyword', 'type', 'start_time', 'end_time');
        $type = trim($request->type);
        $keyword = trim($request->keyword);
        $start_time = $input['start_time'] ? $input['start_time'] : date("Y-m-d", strtotime('-3 days'));
        $end_time = $input['end_time'] ? $input['end_time'] : date('Y-m-d', time());
        $resume = DB::table('personal_users as t1')
            ->join('resume as t2', 't1.uid', '=', 't2.uid')
            ->select(
                't1.uid', 't1.last_login_time', 't1.regtime',
                't2.name', 't2.intentionjobs', 't2.mobile', 't2.id', 't2.updatetime'
            )->where(function($query) use ($keyword){
                if(strlen($keyword) > 0){
                    $query->where('t2.name', 'like', '%' . $keyword . '%')
                        ->orWhere('t2.mobile', 'like', '%' . $keyword . '%');
                }
            })->where(function($query) use ($type){
                if(strlen($type) > 0){
                    $query->where('t2.resume_status', $type);
                }
            })->where(function($query) use ($start_time){
                $query->where('t1.last_login_time', '>=', $start_time);
            })->where(function($query) use ($end_time){
                $query->where('t1.last_login_time', '<=', $end_time);
            })
            ->orderBy('t1.regtime', 'desc')
            ->paginate(20);
        foreach($resume as $v){
            $v->updatetime = timeTranx($v->updatetime);
            $v->regtime = timeTranx($v->regtime);
            $v->last_login_time = timeTranx($v->last_login_time);
        }
        //分页分配参数 过滤boolean假值
        $appends = arrayFilter($input);
        return Style::view('admin.personal_manage.resume_admin_refresh', compact('resume', 'appends', 'type', 'start_time', 'end_time'));
    }

    /**
     * 刷新简历
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function adminResumeRefresh(Request $request){
        $resume_id = $request->input('selected_id.*');
        foreach($resume_id as $k => $v){
            Resume::where('id', $v)->update(['updatetime' => date('Y-m-d H:i:s', time()), 'xs_status' => 0]);
        }
        flash('刷新成功', 'success');
        return redirect('admin/smart_list');
    }

    /**
     * 个人用户删除
     * @param $uid
     * @param null $personal_uid
     * @param null $resume_id
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function jobUserDel($uid, $personal_uid = null, $resume_id = null){
        if(empty($personal_uid)){
            $personal_uid = $uid;
        }
        $resume_id = $resume_id ? explode('+', $resume_id) : [];

        if(empty($resume_id)){
            $resume_id = Resume::where('uid', $uid)->pluck('id')->toArray();
        }
        $num = 0;
        $arr_resume_id = ['resume_complain', 'resume_favorite', 'resume_remark'];
        if(!empty($resume_id)){
            foreach($resume_id as $r){
                foreach($arr_resume_id as $value){
                    $num += DB::table($value)->where('resume_id', $r)->delete();
                }
            }

            //删除迅搜中的简历
            ResumeXS::deleteResume($resume_id);
        }
        $arr_personal_uid = ['browse_company', 'browse_job', 'browse_resume', 'buy_resume', 'interview',
            'part_time_sign_process', 'part_time_sign_up', 'resume_send', 'shieldcompanies'];
        foreach($arr_personal_uid as $value){
            $num += DB::table($value)->where('personal_uid', $personal_uid)->delete();
        }
        $arr_uid = ['apm', 'favorites', 'part_time_resume', 'personal_login_record', 'personal_password_resets', 'resume_certificate',
            'resume_education_exp', 'resume_language_skill', 'resume_other', 'resume_project_exp', 'resume_skill', 'resume_work_exp',
            'resume_works', 'resume_works_img', 'search_engine', 'resume', 'personal_users'];
        foreach($arr_uid as $value){
            $num += DB::table($value)->where('uid', $uid)->delete();
        }
        if($num > 0){
            $resume_id = implode('+', $resume_id);
            return redirect('admin/com_user_del/' . $uid . '/' . $personal_uid . '/' . $resume_id);
        }else{
            return response()->json(['status' => 0, 'msg' => '用户删除成功']);
        }
    }
}